package com.hongye.why.base.net;

import com.alibaba.fastjson.JSON;
import com.hongye.why.app.AppManager;
import com.hongye.why.base.LifeSubscriber;
import com.hongye.why.base.TaskPool;
import com.hongye.why.util.LogUtil;

import java.io.IOException;
import java.io.Serializable;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * http 请求
 */
public class OKHttpRequest implements IRequest {
    /**
     * 生命载体
     */
    private final LifeSubscriber lifeSubscriber;
    /**
     *
     */
    private final OkHttpClient client;
    /**
     * 一次请求
     */
    private Call call;
    /**
     *
     */
    private Request request;
    /**
     * 请求响应处理
     */
    private ResponseHandler responseHandler;

    /**
     * @param lifeSubscriber LifeSubscriber
     * @param client         OkHttpClient
     */
    public OKHttpRequest(LifeSubscriber lifeSubscriber, OkHttpClient client) {
        this.lifeSubscriber = lifeSubscriber;
        this.client = client;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    @Override
    public void cancel() {
        lifeEnd();
    }

    @Override
    public void execute(final ResponseHandler responseHandler) {
        this.responseHandler = responseHandler;
        if (responseHandler != null) {
            responseHandler.onNetStart();
        }
        if (client != null) {
            call = client.newCall(request);
            lifeStart();
        } else {
            if (responseHandler != null) {
                responseHandler.onEnd();
            }
        }
    }

    @Override
    public void lifeStart() {
        if (lifeSubscriber != null) {
            lifeSubscriber.attach(this);
        }
        if (call != null && !call.isExecuted()) {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //TODO 最好根据不同异常显示不同提示信息，不要统一“服务器繁忙”
                    if (responseHandler != null) {
                        TaskPool.myPool().postTaskOnMain(new Runnable() {
                            @Override
                            public void run() {
                                responseHandler.onFail(-1, "服务器繁忙");
                            }
                        });
                    }
                    lifeEnd();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String result = response.body().string();
                    //如果结果是xml格式直接返回，执行请求响应处理工具的成功后的操作
                    if(result.startsWith("<?xml")){
                        if (responseHandler != null) {
                            TaskPool.myPool().postTaskOnMain(new Runnable() {
                                @Override
                                public void run() {
                                    responseHandler.onSuccess(result);
                                }
                            });
                        }
                    //如果响应结果为JSON格式则执行JSON的转换操作
                    //TODO 不同API响应格式可能不一样
                    } else {
                        if (responseHandler != null) {
                            try {
                                final ResultJson resultJson = JSON.parseObject(result, ResultJson.class);
                                if (resultJson != null) {
                                    if (resultJson.code != 0) {
                                        TaskPool.myPool().postTaskOnMain(new Runnable() {
                                            @Override
                                            public void run() {
                                                if (resultJson.code == -2) {
                                                    AppManager.getManager().pushOut();
                                                } else {
                                                    responseHandler.onFail(resultJson.code, resultJson.message);
                                                }
                                            }
                                        });
                                    } else {
                                        final Object t = responseHandler.parseResult(resultJson.body);
                                        TaskPool.myPool().postTaskOnMain(new Runnable() {
                                            @Override
                                            public void run() {
                                                responseHandler.onSuccess(t);
                                            }
                                        });
                                    }
                                } else {
                                    TaskPool.myPool().postTaskOnMain(new Runnable() {
                                        @Override
                                        public void run() {
                                            //未知错误
                                            responseHandler.onFail(-10, "服务器繁忙");
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                TaskPool.myPool().postTaskOnMain(new Runnable() {
                                    @Override
                                    public void run() {
                                        responseHandler.onFail(-10, "服务器繁忙");

                                    }
                                });
                            }
                        }
                    }
                    lifeEnd();
                }
            });
        }
    }

    @Override
    public void lifeEnd() {
        if (call != null && call.isExecuted()) {
            call.cancel();
        }
        if (lifeSubscriber != null) {
            lifeSubscriber.detach(this);
        }
        call = null;
        TaskPool.myPool().postTaskOnMain(new Runnable() {
            @Override
            public void run() {
                responseHandler.onEnd();
                responseHandler = null;
            }
        });
    }

    /**
     * API响应结果公共格式
     * //TODO 不同API响应结果可能不一样
     */
    public static class ResultJson implements Serializable {
        public int code;
        public String message;
        public String body;
    }
}
